package tech.dongliang.juduocai.upload.controller;

import com.alibaba.fastjson.JSONObject;
import tech.dongliang.juduocai.upload.controller.utils.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value = "/upload")
public class FileUploadController {
    @Value("${file.upload.root}")
    private String root;

    /**
     * 上传图片方法
     *
     * @param request
     * @return
     * @throws NumberFormatException
     * @throws Exception
     */
    @PostMapping(value = "/file/{pathfix}")
    @ResponseBody
    public JSONObject img(HttpServletRequest request, @PathVariable("pathfix") String pathfix) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile imgFile = multipartRequest.getFileMap().entrySet().iterator().next().getValue();
        request.setAttribute("root", root);
        request.setAttribute("pathfix", pathfix);
        String[] paths = FileUtils.getSavePathByRequest(request, false);
        JSONObject json = FileUtils.saveFile(imgFile, paths);
        return json;
    }
}
